package cn.com.cetccst.mqtt;

import android.os.Bundle;
import android.os.Looper;
import android.view.View;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import org.eclipse.paho.client.mqttv3.IMqttMessageListener;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;

public class MainActivity extends AppCompatActivity {
    private static final String srv = "172.18.34.110";
    private MqttEngine engine = new MqttEngine();
    private TextView logView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        logView = findViewById(R.id.logView);

        findViewById(R.id.connectBtn).setOnClickListener(this::doConnect);
        findViewById(R.id.clearBtn).setOnClickListener(this::doClear);
        try {
            MessageTopicListener listener = new MessageTopicListener();
            engine.init(this, MqttEngine.getClientID(this), String.format("tcp://%s:1883", srv), state -> log(state.name()));
            engine.addSubscriber("topic/+", 2, listener);
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        try {
            engine.disconnect();
        } catch (MqttException e) {
        }
    }

    private void doConnect(View view) {
        try {
            engine.connect();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void doClear(View view) {
        logView.setText("");
    }

    private void log(final String log) {
        if (Looper.getMainLooper() == Looper.myLooper()) {
            logView.setText(logView.getText() + log + "\n");
        } else {
            runOnUiThread(() -> log(log));
        }
    }

    private class MessageTopicListener implements IMqttMessageListener {

        @Override
        public void messageArrived(String topic, MqttMessage message) throws Exception {
            log(String.format("topic[%s], message[%s]", topic, new String(message.getPayload())));
            //此函数如果抛出异常，服务器会重发此消息
        }
    }
}